// pages/register/register.js
Page({
    data: {
      username: '',
      password: '',
      confirmPassword: '',
      gender: '',
      isRegisterDisabled: true
    },
  
    onUsernameInput(e) {
      this.setData({
        username: e.detail.value
      });
      this.checkRegisterButton();
    },
  
    onPasswordInput(e) {
      this.setData({
        password: e.detail.value
      });
      this.checkRegisterButton();
    },
  
    onConfirmPasswordInput(e) {
      this.setData({
        confirmPassword: e.detail.value
      });
      this.checkRegisterButton();
    },
  
    onSelectGender(e) {
      const gender = e.currentTarget.dataset.gender;
      this.setData({
        gender: gender
      });
      this.checkRegisterButton();
    },
  
    checkRegisterButton() {
      const { username, password, confirmPassword, gender } = this.data;
      const isUsernameValid = username.length >= 4 && username.length <= 20;
      const isPasswordValid = password.length >= 6;
      const isConfirmValid = password === confirmPassword && confirmPassword.length > 0;
      const isGenderSelected = gender !== '';
      
      this.setData({
        isRegisterDisabled: !(isUsernameValid && isPasswordValid && isConfirmValid && isGenderSelected)
      });
    },
  
    onRegister() {
      const { username, password, confirmPassword, gender } = this.data;
      
      if (username.length < 4 || username.length > 20) {
        wx.showToast({
          title: '账号长度为4-20位',
          icon: 'none'
        });
        return;
      }
  
      if (password.length < 6) {
        wx.showToast({
          title: '密码至少6位',
          icon: 'none'
        });
        return;
      }
  
      if (password !== confirmPassword) {
        wx.showToast({
          title: '两次密码不一致',
          icon: 'none'
        });
        return;
      }
  
      if (!gender) {
        wx.showToast({
          title: '请选择性别',
          icon: 'none'
        });
        return;
      }
  
      // 检查账号是否已存在
      const users = wx.getStorageSync('users') || [];
      const existingUser = users.find(user => user.username === username);
      if (existingUser) {
        wx.showToast({
          title: '账号已存在',
          icon: 'none'
        });
        return;
      }
  
      wx.showLoading({
        title: '注册中...',
      });
  
      // 保存用户信息到本地存储（模拟数据库）
      const newUser = {
        username: username,
        password: password,
        gender: gender,
        createTime: new Date().toISOString()
      };
      
      users.push(newUser);
      wx.setStorageSync('users', users);
  
      setTimeout(() => {
        wx.hideLoading();
        wx.showToast({
          title: '注册成功',
          icon: 'success',
          success: () => {
            wx.navigateBack();
          }
        });
      }, 1500);
    },
  
    onBackToLogin() {
      wx.navigateBack();
    },
  
    onGoLogin() {
      wx.navigateBack();
    }
  })